<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ page import="java.io.*,java.util.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>

<%@page import="com.buvaka.UpdateCategoriesFile"%>


<%@page import="java.net.UnknownHostException"%>
<%@ page import = "com.mongodb.*" %>

<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8"/>
    <title>Добавить категорию объектов</title>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>


<script>
        function addInput() {
    /* default-id — hidden elem for IDs */
    var id = document.getElementById("default-id").value;
    id++;
    /* adding new elem */
    $("form[name=main]").append('<div id="div-' + id + '"><input name="input-' + id + '" id="input-' + id + '" value="' + id + '"><input name="input-' + id+10 + '" type="file"><a href="javascript:{}" onclick="removeInput(\'' + id + '\')">Удалить</a></div>');
    /* increase elems count */
    document.getElementById("default-id").value = id;
    }
	
	function removeInput(id) {
		$("#div-" + id).remove();
	}
	
	
</script>

<h3> Выберите картинку для иконки </h3>
<form name="main" action="AddCategory.jsp" method="post" enctype="multipart/form-data">
    <input type="hidden" id="default-id" value="0">
    Имя: <input type="text" name="name" />
    <br/>
    <input type="file" name="file" />
    <input type="submit" value="Сохранить" />
    <br/><a href="javascript:{}" onclick="addInput()">Добавить состояние</a><br>
</form>


<%
	BasicDBObject obj = new BasicDBObject();
    String UPLOAD_DIRECTORY = "src/main/webapp/img/objCats";
    String IMG_DIRECTORY = "img/objCats";
    //load image and name of category
    if(ServletFileUpload.isMultipartContent(request)){
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        //out.println(items.size());
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                String fieldname = item.getFieldName();
                String fieldvalue = item.getString();
                if(fieldname.equals("name")){
                	//TODO Hard hack to get Unicode symbols. Must be changed later.
                    obj.append("_id", new String (fieldvalue.getBytes ("iso-8859-1"), "UTF-8"));  
                   
                }

            } else {
                // Process form file field (input type="file").
                String name = new File(item.getName()).getName();
                item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                obj.append("picture", new File(IMG_DIRECTORY + File.separator + name).getPath().replaceAll("\\\\", "/"));
            }
        }

        if(!obj.equals(new BasicDBObject())){ // If in prevoius IF-statement condition wasn't false
            try{
                MongoClient client = new MongoClient();
                DB db = client.getDB("gis");
                DBCollection categories = db.getCollection("categories");

                categories.insert(obj);
                
                UpdateCategoriesFile.update(client);

            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }

    }
%>

</body>
</html>
